package com.ss.service.impl;

import com.ss.dao.LoginUserDao;
import com.ss.dao.UserDao;
import com.ss.pojo.User;
import com.ss.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;

	@Autowired
	private LoginUserDao loginUserDao;

//考虑到在线人数应该写多于读，所以采用 Collections.synchronizedList而不是CopyOnWriteArrayList
	private static List<String> onlineUserList= Collections.synchronizedList(new ArrayList<String>());


	@Override
	public User validateUser(String userID, String userPassword) {
		return userDao.queryUserByIDAndPassword(userID,userPassword);
	}

	@Override
	public boolean isExistUser(String userID) {
		User user = userDao.queryUserByID(userID);
		return user!=null;
	}

	@Override
	public void register(String userID, String userPassword) {
		userDao.addUser(userID,userPassword);
	}

	@Override
	public User queryUserByID(String userID) {
		return userDao.queryUserByID(userID);
	}

	@Override
	public Integer getOnlineUsersNumber() {
		return loginUserDao.getOnlineUsersNumber();
	}

	@Override
	public void addLoginUser(String userID, Date date) {
		loginUserDao.addLoginUser(userID,date);
	}

	@Override
	public boolean isOnline(String userID) {
		getOnlineUserList();
		if (onlineUserList.contains(userID)) {
			return true;
		}
		return false;
	}

	private void getOnlineUserList() {
		onlineUserList = loginUserDao.getOnlineUserList();
	}

}
